package com.sky.service.impl;

import com.sky.constant.OrderConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.OrderPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.Order;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.UserMapper;
import com.sky.po.OrderStatisticsPO;
import com.sky.po.TurnoverStatisticsPO;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 工作台业务接口实现类
 */
@Service
@Slf4j
public class WorkspaceServiceImpl implements WorkspaceService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 根据时间段统计营业数据
     *
     * @param today 当天的日期
     * @return
     */
    @Override
    public BusinessDataVO getBusinessData(LocalDate today) {
        /**
         * 营业额：当日已完成订单的总金额
         * 有效订单：当日已完成订单的数量
         * 订单完成率：有效订单数 / 总订单数
         * 平均客单价：营业额 / 有效订单数
         * 新增用户：当日新增用户的数量
         */

        LocalDateTime begin = LocalDateTime.of(today, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(today, LocalTime.MAX);

        //查询总订单数、有效订单数
        List<OrderStatisticsPO> orderStatisticsPOS = orderMapper.listOrderConutByDay(begin, end);

        int totalOrderCount = 0;
        int validOrderCount = 0;
        if (orderStatisticsPOS.size() > 0) {
            totalOrderCount = orderStatisticsPOS.get(0).getOrderCount();
            validOrderCount = orderStatisticsPOS.get(0).getValidOrderCount();
        }


        //营业额
        Double turnover = 0.0;
        List<TurnoverStatisticsPO> turnoverStatisticsPOS = orderMapper.listTurnoverByDay(begin, end);
        String turnoverStr = null;
        if (turnoverStatisticsPOS.size() > 0) {
            turnoverStr = turnoverStatisticsPOS.get(0).getValue();
        }
        if (turnoverStr != null) {
            turnover = Double.valueOf(turnoverStr);
        }


        // 计算订单完成率和客单价
        Double unitPrice = 0.0;
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0 && validOrderCount != 0) {
            //订单完成率
            orderCompletionRate = validOrderCount / (totalOrderCount + 0.0);
            //平均客单价
            unitPrice = BigDecimal.valueOf(turnover).
                    divide(BigDecimal.valueOf(validOrderCount), 2, RoundingMode.HALF_UP).doubleValue();

        }

        //新增用户数
        Integer newUsers = userMapper.countNewByCreateDate(begin.toLocalDate());

        return BusinessDataVO.builder()
                .turnover(turnover)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .unitPrice(unitPrice)
                .newUsers(newUsers)
                .build();
    }


    /**
     * 查询订单管理数据
     *
     * @param today 当天的日期
     * @return
     */
    @Override
    public OrderOverViewVO getOrderOverView(LocalDate today) {

        // 处理时间
        LocalDateTime todayTime = LocalDateTime.of(today, LocalTime.MIN);

        // 查询今天所有订单
        List<Order> orders = orderMapper.listByConditions(OrderPageQueryDTO.builder().beginTime(todayTime).build());

        AtomicInteger waitingOrders = new AtomicInteger(0);// 待接单
        AtomicInteger toBedeliveredOrders = new AtomicInteger(0);// //待派送
        AtomicInteger completedOrders = new AtomicInteger(0);// //已完成
        AtomicInteger cancelledOrders = new AtomicInteger(0);// //已取消
        Integer allOrders = 0;              //
        // 遍历集合，分别统计各个状态的订单数量
        if (orders != null && orders.size() > 0) {
            allOrders = orders.size();
            orders.forEach(order -> {
                if (OrderConstant.TO_BE_CONFIRMED.equals(order.getStatus())) {
                    waitingOrders.addAndGet(1);
                } else if (OrderConstant.CONFIRMED.equals(order.getStatus())) {
                    toBedeliveredOrders.addAndGet(1);
                } else if (OrderConstant.COMPLETED.equals(order.getStatus())) {
                    completedOrders.addAndGet(1);
                } else if (OrderConstant.CANCELLED.equals(order.getStatus())) {
                    cancelledOrders.addAndGet(1);
                }
            });
        }


        return OrderOverViewVO.builder()
                .waitingOrders(waitingOrders.get())
                .deliveredOrders(toBedeliveredOrders.get())
                .completedOrders(completedOrders.get())
                .cancelledOrders(cancelledOrders.get())
                .allOrders(allOrders)
                .build();
    }

    /**
     * 查询菜品总览
     *
     * @return
     */
    @Override
    public DishOverViewVO getDishOverView() {

        List<DishVO> dishVOS = dishMapper.selectByCondition(new Dish());


        Integer enabledCount = 0;
        Integer disableCount = 0;
        if (dishVOS != null && dishVOS.size() > 0) {

            for (DishVO dishVO : dishVOS) {
                if (StatusConstant.ENABLE.equals(dishVO.getStatus())) {
                    enabledCount += 1;
                } else /* if (StatusConstant.DISABLE.equals(dishVO.getStatus()))  */ {
                    disableCount += 1;
                }
            }
        }

        return DishOverViewVO.builder()
                .sold(enabledCount)
                .discontinued(disableCount)
                .build();
    }

    /**
     * 查询套餐总览
     *
     * @return
     */
    @Override
    public SetmealOverViewVO getSetmealOverView() {

        List<Setmeal> setmeals = setmealMapper.listByCondition(new Setmeal());


        Integer enabledCount = 0;
        Integer disableCount = 0;
        if (setmeals != null && setmeals.size() > 0) {
            for (Setmeal setmeal : setmeals) {
                if (StatusConstant.ENABLE.equals(setmeal.getStatus())) {
                    enabledCount += 1;
                } else /* if (StatusConstant.DISABLE.equals(setmeal.getStatus()))  */ {
                    disableCount += 1;
                }
            }
        }

        return SetmealOverViewVO.builder()
                .sold(enabledCount)
                .discontinued(disableCount)
                .build();
    }
}
